package com.yvan.cs.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.yvan.cs.platform.JsonWapper;
import com.yvan.cs.platform.YvanUtil;
import lombok.SneakyThrows;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;

import java.io.StringWriter;
import java.util.Map;

public class VelocityUtils {
    public volatile static VelocityUtils INSTANCE = new VelocityUtils();

    private final VelocityEngine velocityEngine;

    private VelocityUtils() {
        velocityEngine = new VelocityEngine();
        // 修复部分用户的velocity日志记录无权访问velocity.log文件问题
        velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.Log4JLogChute");
        velocityEngine.setProperty("runtime.log.logsystem.log4j.logger", "velocity");
    }

    /**
     * 渲染模板
     *
     * @param template 模板字符串
     * @param map      参数集合
     * @return 渲染结果
     */
    @SneakyThrows
    public String generate(String template, Map<String, Object> map) {
        VelocityContext velocityContext = new VelocityContext();
        if (map != null) {
            map.forEach(velocityContext::put);
        }
        try (StringWriter stringWriter = new StringWriter()) {
            // 设置编码
            velocityEngine.setProperty(VelocityEngine.INPUT_ENCODING, "UTF-8");
            velocityEngine.setProperty(VelocityEngine.OUTPUT_ENCODING, "UTF-8");
            // 生成代码
            velocityEngine.evaluate(velocityContext, stringWriter, "CodeSlave-Code-Generate", template);
            // 返回结果
            return stringWriter.toString();
        }
    }
}
